/*
 * BanBu_NameAndSexController
 * @description 本文件提供个人空间个人资料修改名称和性别的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供个人空间个人资料修改名称和性别的ViewController
 */

#import "BanBu_NameAndSexController.h"
#import "BanBu_BloodTypeAndHeightController.h"
#import "AppDataManager.h"
#import "TKLoadingView.h"
#import "BanBu_NavButton.h"
#import "BanBu_ImageView.h"
#import "CJSONDeserializer.h"
#import "CJSONSerializer.h"
#import "GTMBase64.h"
#import "NSData+Base64.h"
@interface BanBu_NameAndSexController ()

@end

@implementation BanBu_NameAndSexController

@synthesize viewType = _viewType;
@synthesize name = _name;
@synthesize sex = _sex;

// 获取当前机器语言
-(NSString*)getPreferredLanguage
{
    NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
    NSArray* languages = [defs objectForKey:@"AppleLanguages"];
    NSString* preferredLang = [languages objectAtIndex:0];
    return preferredLang;
}

- (id)initWithViewType:(NameAndSexViewType)type
{
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {

        _viewType = type;
    }
    return self;
}
-(void)popself
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    UILabel *lab = (UILabel *)[self.navigationController.navigationBar viewWithTag:10000];
    [lab removeFromSuperview];
    UILabel *lab1 = (UILabel *)[self.navigationController.navigationBar viewWithTag:10001];
    [lab1 removeFromSuperview];
}

-(void)viewWillAppear:(BOOL)animated
{
    [UIView setAnimationsEnabled:YES];
    [super viewWillAppear:YES];
    /*
    NSString *title = nil;
    if(self.viewType == NameAndSexViewNameOnlyType)
    {
        title = NSLocalizedString(@"nameAndSexTitle", nil);
    }
    else
    {
        title = [NSString stringWithFormat:@"%@(2/5)",NSLocalizedString(@"nameAndSexTitle", nil)];
    }
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 44)];
    lab.text = title;
    lab.lineBreakMode = kTextLineBreakByWordWrapping;
    [self.navigationController.navigationBar addSubview:lab];
    lab.center = CGPointMake(self.navigationController.navigationBar.frame.size.width/2, 22);
    lab.textAlignment = kTextAlignmentCenter;
    CGFloat height = [lab.text sizeWithFont:[UIFont fontWithName:@"TrebuchetMS-Bold" size:18] constrainedToSize:CGSizeMake(150, 44) lineBreakMode:kTextLineBreakByWordWrapping].height;
    lab.font = [UIFont  fontWithName:@"TrebuchetMS-Bold" size:height>21?15:18];
//    lab.adjustsFontSizeToFitWidth = YES;
    lab.backgroundColor = [UIColor clearColor];
    lab.numberOfLines = 2;
    lab.textColor = [UIColor whiteColor];

    lab.tag = 10000;
    [lab release];
    */
    /**/
    NSString *title = nil;
    
    if(self.viewType == NameAndSexViewNameOnlyType)
    {
        title = NSLocalizedString(@"nameAndSexTitle", nil);
        
        UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 44)];
        lab.text = title;
        lab.lineBreakMode = kTextLineBreakByWordWrapping;
        [self.navigationController.navigationBar addSubview:lab];
        lab.center = CGPointMake(self.navigationController.navigationBar.frame.size.width/2, 22);
        lab.textAlignment = kTextAlignmentCenter;
        CGFloat height = [lab.text sizeWithFont:[UIFont fontWithName:@"TrebuchetMS-Bold" size:18] constrainedToSize:CGSizeMake(150, 44) lineBreakMode:kTextLineBreakByWordWrapping].height;
        lab.font = [UIFont  fontWithName:@"TrebuchetMS-Bold" size:height>21?15:18];
        //    lab.adjustsFontSizeToFitWidth = YES;
        lab.backgroundColor = [UIColor clearColor];
        lab.numberOfLines = 2;
        lab.textColor = [UIColor whiteColor];
        
        lab.tag = 10000;
        [lab release];
    }
    else
    {
        title = [NSString stringWithFormat:@"%@",NSLocalizedString(@"nameAndSexTitle", nil)];
        UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 160,22)];
        lab.text = title;
        lab.lineBreakMode = kTextLineBreakByTruncatingTail;
        [self.navigationController.navigationBar addSubview:lab];
        lab.center = CGPointMake(160, 11);
        lab.textAlignment = kTextAlignmentCenter;
        lab.backgroundColor = [UIColor clearColor];
        lab.textColor = [UIColor whiteColor];
        lab.font = [UIFont  fontWithName:@"TrebuchetMS-Bold" size:15];
        lab.tag = 10000;
        [lab release];
        
        
        UILabel *lab1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 22)];
        lab1.center = CGPointMake(160, 33);
        lab1.text = @"(2/5)";
        [self.navigationController.navigationBar addSubview:lab1];
        lab1.textAlignment = kTextAlignmentCenter;
        lab1.backgroundColor = [UIColor clearColor];
        lab1.textColor = [UIColor whiteColor];
        lab1.font = [UIFont  fontWithName:@"TrebuchetMS-Bold" size:15];
        lab1.tag = 10001;
        [lab1 release];
    }

    
    

    /**/
    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setUpForDismissKeyboard];
    
    self.tableView.backgroundView = nil;
    self.tableView.backgroundColor = [UIColor colorWithRed:255.0/255 green:250.0/255 blue:240.0/255 alpha:1.0];
    BanBu_ImageView *img  = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable] autorelease];
    self.tableView.backgroundView = img;
    self.tableView.scrollEnabled = NO;

    if(_viewType == NameAndSexViewFullType)
    {
        BanBu_NavButton *nextButton = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
        nextButton.position = ButtonPositionRight;
        nextButton.frame=CGRectMake(0, 0, 60, 30);
        [nextButton addTarget:self action:@selector(nextStep:) forControlEvents:UIControlEventTouchUpInside];
//        [nextButton setTitleEdgeInsets:UIEdgeInsetsMake(3, 2, 2, 2)];
        [nextButton setTitle:@"3/5＞" forState:UIControlStateNormal];
//        nextButton.titleLabel.font = [UIFont  fontWithName:@"TrebuchetMS-Bold" size:18];
        nextButton.titleLabel.font = [UIFont systemFontOfSize:18];
        UIBarButtonItem *next = [[[UIBarButtonItem alloc] initWithCustomView:nextButton] autorelease];
        self.navigationItem.rightBarButtonItem = next;
        [nextButton release];
        
        BanBu_NavButton *returnBtn = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
        returnBtn.position  = ButtonPositionLeft;
        returnBtn.frame=CGRectMake(0, 0, 60, 30);
        [returnBtn addTarget:self action:@selector(popself) forControlEvents:UIControlEventTouchUpInside];
        
        [returnBtn setTitle:@"＜1/5" forState:UIControlStateNormal];
//        returnBtn.titleLabel.font = [UIFont  fontWithName:@"TrebuchetMS-Bold" size:18];
        nextButton.titleLabel.font = [UIFont systemFontOfSize:18];
        UIBarButtonItem *returnItem = [[[UIBarButtonItem alloc] initWithCustomView:returnBtn] autorelease];
        self.navigationItem.leftBarButtonItem = returnItem;
        [returnBtn release];
        
        self.navigationItem.leftBarButtonItem.title = @"＜1/5";
        
    }
    else
    {
        BanBu_NavButton *nextButton = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
        nextButton.position = ButtonPositionRight;
        nextButton.frame=CGRectMake(0, 0, 60, 30);
        [nextButton addTarget:self action:@selector(confirmInfo:) forControlEvents:UIControlEventTouchUpInside];
        [nextButton setTitle:NSLocalizedString(@"确定", nil) forState:UIControlStateNormal];
        nextButton.titleLabel.font = [UIFont  fontWithName:@"TrebuchetMS-Bold" size:18];
        UIBarButtonItem *next = [[[UIBarButtonItem alloc] initWithCustomView:nextButton] autorelease];
        self.navigationItem.rightBarButtonItem = next;
        [nextButton release];
    }
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if(self.viewType == NameAndSexViewNameOnlyType)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"noticeNotice", nil) message:NSLocalizedString(@"labelEditedOnce", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"确定", nil) otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }

}
-(void)confirmInfo:(UIButton *)btn
{
    if(!_sex == _sexSeg.selectedIndex&&[_name isEqualToString:_nameField.text])
    {
        [self popself];
        return;
    }
    if([_delegate respondsToSelector:@selector(banBuTextEditerDidChangeValue:forItem:)])
    {
        [_delegate banBuTextEditerDidChangeValue:_sexSeg.selectedIndex?@"f":@"m" forItem:NSLocalizedString(@"sexSelect", nil)];
        [_delegate banBuTextEditerDidChangeValue:_nameField.text forItem:NSLocalizedString(@"nameLabel", nil)];
    }
    [self popself];
}
- (void)segmentedControlDidChangeValue:(SVSegmentedControl *)seg
{

    if([_nameField isFirstResponder]){
        [_nameField resignFirstResponder];

    }
    if(seg.selectedIndex){
        [seg.thumb setTintColor:[UIColor colorWithRed:221.0/255.0 green:28.0/255.0 blue:19.0/255.0 alpha:1]];

    }else{
        [seg.thumb setTintColor:[UIColor colorWithRed:30.0/255.0 green:100.0/255.0 blue:175.0/255.0 alpha:1]];

    }

}


- (void)viewDidUnload
{
    [super viewDidUnload];
    self.name = nil;
    
}

- (void)dealloc
{

    [_name release],_name = nil;
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(!section)
    {
        return @"";
    }
    else if(section == 2)
    {
        return NSLocalizedString(@"secondStep", nil);
    }
    else
    {
        return NSLocalizedString(@"firstStep", nil);
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(!section)
    {
        return 20;
    }
    else
    {
        return 30;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    if(section==2)
        return NSLocalizedString(@"nameNotice", nil);
    else
        return nil;

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(!indexPath.section)
    {
        CGSize size = [NSLocalizedString(@"changeNotice", nil) sizeWithFont:[UIFont boldSystemFontOfSize:16] constrainedToSize:CGSizeMake(300, 1000) lineBreakMode:kTextLineBreakByWordWrapping];
        return 40+size.height;
    }
    else{
        return 45;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    if(!indexPath.section)
    {

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UILabel *tipLabel= [[UILabel alloc] initWithFrame:CGRectMake(0, 5, 300, 20)];
        tipLabel.backgroundColor = [UIColor clearColor];
        tipLabel.textAlignment = kTextAlignmentCenter;
        tipLabel.textColor = [UIColor blackColor];
        tipLabel.font = [UIFont boldSystemFontOfSize:16];
        tipLabel.text = NSLocalizedString(@"helpfulTitle", nil);
        [cell.contentView addSubview:tipLabel];
        [tipLabel release];
        
        UILabel *helpLabel= [[UILabel alloc] init];
        helpLabel.backgroundColor = [UIColor clearColor];
        helpLabel.textAlignment = kTextAlignmentCenter;
        helpLabel.numberOfLines = 0;
        helpLabel.lineBreakMode = kTextLineBreakByWordWrapping;
        CGSize size = [NSLocalizedString(@"changeNotice", nil) sizeWithFont:[UIFont boldSystemFontOfSize:16] constrainedToSize:CGSizeMake(300, 1000) lineBreakMode:kTextLineBreakByWordWrapping];
        helpLabel.frame = CGRectMake(0, 30, 300,size.height);
        helpLabel.numberOfLines = 2;
        helpLabel.textColor = [UIColor darkGrayColor];
        helpLabel.font = [UIFont boldSystemFontOfSize:16];
        helpLabel.text = NSLocalizedString(@"changeNotice", nil);
        [cell.contentView addSubview:helpLabel];
        [helpLabel release];

    }
    else
        if(indexPath.section==2)
    {
    UITextField *textField = (UITextField *)[cell viewWithTag:111];
    if(!textField)
    {
        textField = [[UITextField alloc] initWithFrame:CGRectMake(100, 10, 180, 25)];
        if(_viewType == NameAndSexViewNameOnlyType)
            textField.frame = CGRectMake(20, 10, 280, 25);
        textField.tag = 111;
        textField.delegate = self;
        textField.backgroundColor = [UIColor clearColor];
        textField.borderStyle = UITextBorderStyleNone;
        textField.textColor = [UIColor colorWithRed:50.0/255 green:79.0/255 blue:133.0/255 alpha:1.0];
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.returnKeyType = UIReturnKeyGo;
        [cell addSubview:textField];
        [textField release];
        if(_viewType == NameAndSexViewFullType)
            cell.textLabel.text = NSLocalizedString(@"nameLabel", nil);
        _nameField = textField;
        textField.placeholder =NSLocalizedString(@"namePlaceholder", nil);
        if(MyAppDataManager.regDic){
            NSData *data = [NSData dataFromBase64String:[MyAppDataManager.regDic valueForKey:@"pname_b64"]];
            NSString *pname_str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            textField.text = pname_str;
        }
        if(_name)
            textField.text = _name;
        }
    }
    else
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UIView *tempView = [[[UIView alloc] init] autorelease];
        [cell setBackgroundView:tempView];
        [cell setBackgroundColor:[UIColor clearColor]];
        NSArray *items = [NSArray arrayWithObjects:[NSString stringWithFormat:@"   ♂ %@     ",NSLocalizedString(@"boy",nil)], [NSString stringWithFormat:@"   ♀ %@        ",NSLocalizedString(@"girl",nil)],nil];
//        NSArray *items = [NSArray arrayWithObjects:[UIImage imageNamed:@"logo.png"],[UIImage imageNamed:@"logo.png"],nil];
   
        SVSegmentedControl *seg = [[SVSegmentedControl alloc] initWithSectionTitles:items];
        seg.center = CGPointMake(160, 25);
        seg.crossFadeLabelsOnDrag = YES;
        [seg.thumb setTintColor:[UIColor colorWithRed:221.0/255.0 green:28.0/255.0 blue:19.0/255.0 alpha:1]];
        seg.backgroundColor = [UIColor colorWithWhite:0 alpha:.2];
//        [seg.thumb setTintColor:[UIColor redColor]];
//        seg.backgroundColor = [UIColor redColor];

        seg.selectedIndex = 0;
        if(MyAppDataManager.regDic){
            NSInteger sexInteger;
            if([[MyAppDataManager.regDic valueForKey:@"gender"] isEqualToString:@"m"]){
                sexInteger = 0;
            }else{
                sexInteger = 1;
            }
            seg.selectedIndex =sexInteger;
        }else{
            seg.selectedIndex =0;
            
        }
        if(self.viewType == NameAndSexViewNameOnlyType)
        {
            seg.selectedIndex = !_sex;
        }
        [seg addTarget:self action:@selector(segmentedControlDidChangeValue:) forControlEvents:UIControlEventValueChanged];
        _sexSeg = seg;
        [cell.contentView addSubview:seg];
        [seg release];
    }
    
    return cell;

}

- (void)nextStep:(UIButton *)button
{
    if(![[_nameField.text stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]] length] )
    {        
        [TKLoadingView showTkloadingAddedTo:self.view point:CGPointMake(0, 140) title:NSLocalizedString(@"namePlaceholder", nil) activityAnimated:NO duration:1.0];
//        [TKLoadingView showTkloadingAddedTo:self.view title:@"请输入您的名字" activityAnimated:NO duration:1.0];
        return;
    }
    NSString *sexStr = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"selectSex", nil),_sexSeg.selectedIndex?NSLocalizedString(@"girl", nil):NSLocalizedString(@"boy", nil)];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"helpfulTitle", nil) message:sexStr delegate:self cancelButtonTitle:NSLocalizedString(@"editSex", nil) otherButtonTitles:NSLocalizedString(@"confirmNotice", nil), nil];
    [alert show];
    [alert release];

    
}

- (void)setName:(NSString *)name
{
    [_name release];
    _name = [name retain];
    [self.tableView reloadData];
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    UITextField *field = (UITextField *)[[self.tableView cellForRowAtIndexPath:indexPath] viewWithTag:111];
    [field becomeFirstResponder];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex){

        [self saveRegisterInfo:[MyAppDataManager IsMinGanWord:_nameField.text] and:_sexSeg.selectedIndex?@"f":@"m"];
        BanBu_BloodTypeAndHeightController *blood = [[BanBu_BloodTypeAndHeightController alloc] init];
        [self.navigationController pushViewController:blood animated:YES];
        [blood release];
    }
}
#pragma mark - 保存数据到MyAppDataManager 参数 "pname_b64" "gender"
-(void)saveRegisterInfo:(NSString *)_pname and:(NSString *)_gender
{
    NSString *jsonValue = [[_pname dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    [MyAppDataManager.regDic setValue:jsonValue forKey:@"pname_b64"];
    [MyAppDataManager.regDic setValue:_gender forKey:@"gender"];
}

- (void)setUpForDismissKeyboard {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(tapAnywhereToDismissKeyboard:)];
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view addGestureRecognizer:singleTapGR];
                }];
    [nc addObserverForName:UIKeyboardWillHideNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view removeGestureRecognizer:singleTapGR];
                }];
}

- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
    //此method会将self.view里所有的subview的first responder都resign掉
    [self.view endEditing:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if(_viewType == NameAndSexViewNameOnlyType)
    {
        [self confirmInfo:nil];
        return YES;
    }
    else
    {
        [self nextStep:nil];
        return YES;
    }

}
@end
